<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="分类名称" prop="categoryName">
                <el-input
                    v-model="queryParams.categoryName"
                    placeholder="请输入分类名称"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item label="分类状态" prop="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="请选择分类状态"
                    clearable
                >
                    <el-option label="正常" value="0" />
                    <el-option label="停用" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-card class="base-table" ref="fullTable">
            <TableSetup
                ref="tSetup"
                @onStripe="onStripe"
                @onRefresh="onRefresh"
                @onChange="onChange"
                @onfullTable="onfullTable"
                @onSearchChange="onSearchChange"
                :columns="columns"
                :isTable="isTable"
            >
                <template v-slot:operate>
                    <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['file:category:add']"
                        >新增</el-button
                    >
                    <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['file:category:edit']"
                        >修改</el-button
                    >
                    <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['file:category:remove']"
                        >删除</el-button
                    >
                    <el-button
                        type="primary"
                        plain
                        icon="Upload"
                        @click="handleImport"
                        v-hasPermi="['file:category:import']"
                        >导入</el-button
                    >
                    <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['file:category:export']"
                        >导出</el-button
                    >
                </template>
            </TableSetup>
            <auto-table
                ref="multipleTable"
                class="mytable"
                :tableData="categoryList"
                :columns="columns"
                :loading="loading"
                :stripe="stripe"
                :tableHeight="tableHeight"
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                row-key="id"
                default-expand-all
                @onColumnWidthChange="onColumnWidthChange"
                @onSelectionChange="handleSelectionChange"
            >
                <template #status="{ row }">
                    <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                        {{ row.status === '0' ? '正常' : '停用' }}
                    </el-tag>
                </template>
                <template #updateTime="{ row }">
                    <span>{{ parseTime(row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
                <template #operate="{ row }">
                    <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click="handleUpdate(row)"
                        v-hasPermi="['file:category:edit']"
                        >修改</el-button
                    >
                    <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(row)"
                        v-hasPermi="['file:category:remove']"
                        >删除</el-button
                    >
                </template>
            </auto-table>
            <div class="table-pagination">
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
                />
            </div>
        </el-card>

        <!-- 添加或修改文件分类对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form
                ref="categoryRef"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="父级分类" prop="parentId">
                    <el-tree-select
                        v-model="form.parentId"
                        :data="categoryTreeOptions"
                        :props="{
                            value: 'id',
                            label: 'categoryName',
                            children: 'children'
                        }"
                        value-key="id"
                        placeholder="请选择父级分类（不选择则为顶级分类）"
                        check-strictly
                        clearable
                    />
                    <div class="form-tip">
                        <el-text type="info" size="small">
                            不选择父级分类则创建顶级分类
                        </el-text>
                    </div>
                </el-form-item>

                <el-form-item label="分类名称" prop="categoryName">
                    <el-input
                        v-model="form.categoryName"
                        placeholder="请输入分类名称"
                    />
                </el-form-item>

                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number
                        v-model="form.orderNum"
                        :min="0"
                        placeholder="请输入显示顺序"
                    />
                </el-form-item>

                <el-form-item label="分类状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio label="0">正常</el-radio>
                        <el-radio label="1">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入数据对话框 -->
        <ImportData
            v-if="openImport"
            v-model="openImport"
            tableName="bg_file_category"
            @success="handleImportSuccess"
        />
    </div>
</template>

<script setup name="BgFileCategory">
import {
    listCategory,
    getCategory,
    delCategory,
    addCategory,
    updateCategory,
    importCategory,
    getCategoryTree
} from '@/api/file/category'
import { listAllTable } from '@/api/system/table'
import TableSetup from '@/components/TableSetup'
import AutoTable from '@/components/AutoTable'
import ImportData from '@/components/ImportData'
const { proxy } = getCurrentInstance()

const categoryList = ref([])
const categoryTreeOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const columns = ref([])
const stripe = ref(true)
const isTable = ref(true)
const tableHeight = ref(500)
const fullScreen = ref(false)
const openImport = ref(false)

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryName: null,
        status: null
    },
    rules: {
        categoryName: [
            { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        orderNum: [
            { required: true, message: '显示顺序不能为空', trigger: 'blur' }
        ],
        status: [
            { required: true, message: '分类状态不能为空', trigger: 'change' }
        ]
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询文件分类列表 */
function getList() {
    loading.value = true
    getCategoryTree(queryParams.value).then((response) => {
        categoryList.value = response.data
        total.value = response.data.length
        loading.value = false
    })
}

/** 获取分类树选项 */
function getCategoryTreeOptions() {
    getCategoryTree().then((response) => {
        categoryTreeOptions.value = response.data
    })
}

function getColumns() {
    listAllTable({ tableName: 'bg_file_category' })
        .then((response) => {
            columns.value = response.data
        })
        .then(() => {
            getList()
            getCategoryTreeOptions()
        })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        parentId: null, // 顶级分类的parentId为null
        categoryName: null,
        orderNum: 0,
        status: '0',
        ancestors: null,
        fileCount: 0
    }
    proxy.resetForm('categoryRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getCategoryTreeOptions()
    open.value = true
    title.value = '添加文件分类'
}

/** 新增按钮操作 */
function handleImport() {
    openImport.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    getCategoryTreeOptions()
    const bgFileCategoryId = row.id || ids.value
    getCategory(bgFileCategoryId).then((response) => {
        form.value = response.data
        open.value = true
        title.value = '修改文件分类'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['categoryRef'].validate((valid) => {
        if (valid) {
            if (form.value.id != null) {
                updateCategory(form.value).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addCategory(form.value).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal
        .confirm('是否确认删除文件分类编号为"' + _ids + '"的数据项？')
        .then(function () {
            return delCategory(_ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'file/category/export',
        {
            ...queryParams.value
        },
        `category_${new Date().getTime()}.xlsx`
    )
}

//表格全屏
function onfullTable() {
    proxy.$refs.tSetup.onFull(proxy.$refs.fullTable.$el)
    fullScreen.value = !fullScreen.value
    updateTableHeight()
}
//表格刷新
function onRefresh() {
    getList()
}
//搜索框显示隐藏
function onSearchChange() {
    showSearch.value = !showSearch.value
}

function onStripe(val) {
    stripe.value = val
}
//改变表头数据
function onChange(val) {
    columns.value = val
}

//改变表格宽度
function onColumnWidthChange(column) {
    proxy.$refs.tSetup.tableWidth(column)
}

//更新表格高度
function updateTableHeight() {
    if (
        proxy.$refs.tSetup &&
        proxy.$refs.queryRef &&
        document.querySelector('.table-pagination')
    ) {
        if (fullScreen.value) {
            tableHeight.value = window.innerHeight - 145
        } else {
            tableHeight.value =
                window.innerHeight -
                proxy.$refs.tSetup.$el.clientHeight -
                proxy.$refs.queryRef.$el.clientHeight -
                document.querySelector('.table-pagination').clientHeight -
                220
        }
    }
}
//导入成功
function handleImportSuccess(sheetName, filedInfo, fileName) {
    let data = {
        tableName: 'bg_file_category',
        filedInfo: filedInfo,
        fileName: fileName,
        sheetName: sheetName
    }
    importCategory(data).then(() => {
        proxy.$modal.msgSuccess('导入成功')
        openImport.value = false
        getList()
    })
    getList()
}

onMounted(() => {
    updateTableHeight() // 初始化计算高度
    window.addEventListener('resize', updateTableHeight) // 监听窗口大小变化
})

onUnmounted(() => {
    window.removeEventListener('resize', updateTableHeight) // 销毁监听
})

getColumns()
</script>

<style scoped>
.form-tip {
    margin-top: 5px;
}
</style>